package net.libra.loader
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * 队列加载xml
	 * @author elvisjiang
	 */
	public class XmlLoader extends EventDispatcher
	{
		private var nameArray:Array;
		private var pathArray:Array;
		private var _xmlArray:Array;
		private var currentIndex:int;
		private var loader:URLLoader;
		
		public function XmlLoader()
		{
			this._xmlArray = [];
			this.pathArray = [];
			this.nameArray = [];
			this.currentIndex = -1;
		}
		
		public function addURL(name:String, url:String):void
		{
			var i:int = 0;
			for(i = 0;i<pathArray.length;i++)
			{
				if(pathArray[i] == url)
				{
					return;
				}
			}
			for(i = 0;i<nameArray.length;i++)
			{
				if(nameArray[i] == name)
				{
					return;
				}
			}
			this.nameArray.push(name);
			this.pathArray.push(url);
		}
		
		public function start():void
		{
			if(this.currentIndex == -1)
			{
				this.run();
			}
		}
		
		private function run():void
		{
			this.currentIndex++;
			
			var url:String = this.pathArray[this.currentIndex];
			if(url && url != "")
			{
				loader = new URLLoader();
				loader.addEventListener(Event.COMPLETE, __onResult);
				loader.addEventListener(IOErrorEvent.IO_ERROR,__onResult);
			
				loader.load(new URLRequest(url));
		
			}
			else
			{
				currentIndex = -1;
				this.dispatchEvent(new LoadEvent(LoadEvent.ON_COMPLETE,null));
				Log.info("[XmlLoader] AllItemsLoaded");
			}
		}
		
		
		private function __onResult(event:Event):void
		{
			if(event.type == IOErrorEvent.IO_ERROR)
			{
				throw new Error("地址错误");
				this.currentIndex = -1;
				finalizeLoader();
			}
			else if(event.type == Event.COMPLETE )
			{
				var xml:XML = new XML(loader.data);
				_xmlArray[nameArray[currentIndex]] = xml;
				Log.info("[XmlLoader] Loaded " +this.pathArray[this.currentIndex]);
				finalizeLoader();
				this.run();
			}
		}
		
		public function get(name:String):XML
		{
			return _xmlArray[name];
		}
		
		private function finalizeLoader():void
		{
			loader.removeEventListener(Event.COMPLETE, __onResult);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, __onResult);
			loader = null;
		}
		
		public function get xmlArray():Array
		{
			return _xmlArray;
		}
		
	}
}